<template>
  <view class="ditu" :style="{ height: height + 'px' }">
    <view class="canvas-view">
      <canvas canvas-id="watermarkCanvas" class="canvas"> </canvas>
    </view>

    <view class="ditu_box">
      <view class="flex"> 上传照片</view>
      <u-line margin="20rpx 0rpx"></u-line>
      <view>
        <u-upload :fileList="fileListUrl" @afterRead="afterRead" @delete="deletePic" capture="camera" name="1" :maxCount="3">
          <view class="photoinfo"> <image src="/static/image/pic_icon.png" mode="widthFix"></image></view>
        </u-upload>
      </view>
    </view>
    <view class="ditu_box">
      <view class="row border-bottom">
        <view class="label">地点</view>
        <view class="">{{ address_title }}</view>
      </view>
      <view class="flex j-content row">
        <view class="label">时间</view>
        <view class="">{{ currentDate }}</view>
      </view>
    </view>

    <view class="ditu_box">
      <view>备注</view>
      <u-line margin="20rpx 0rpx"></u-line>
      <view class="ipt textr">
        <u-textarea v-model="remark" placeholder="请输入内容" :border="none"></u-textarea>
      </view>
    </view>

    <view class="bottom">
      <button class="btn back" @click="back">取消</button>
      <button class="btn" @click="submit">保存</button>
    </view>
  </view>
</template>

<script>
import { getScreen, saveImage, curTime, getUserInfo } from '@/service/auth'
import { addWorkLog } from '@/service/api/common_down'

import { applyPermission } from '@/utils/permission'
export default {
  components: {},
  data() {
    return {
      longitude: '', //经度
      latitude: '', //纬度
      address: '', //详细地址
      address_title: '', //建筑物地址
      scale: 16, //缩放
      height: 0,
      width: 0,
      marker: [
        {
          id: 0,
          latitude: '', //纬度
          longitude: '', //经度
          alpha: 1, //透明度
          width: 20,
          height: 30,
        },
      ],
      imageurl: '',
      time: '',
      type: '',
      replaceTime: '',
      reason: '',

      typename: '',
      fileListUrl: [],
      currentDate: '',
      user: {},
      remark: '',
      imgUrl: [],
    }
  },
  created() {
    const that = this
    const { width, height } = getScreen()
    this.height = height
    this.width = width
    console.log('-----------width height' + this.width + ',+' + this.height)
    const result = applyPermission('scope.userLocation', '位置权限')

    if (result) {
      that.getLocation()
    }
  },
  onLoad(option) {
    this.currentDate = curTime()
    this.user = getUserInfo()
  },
  methods: {
    getLocation() {
      const that = this
      uni.getLocation({
        type: 'gcj02',

        geocode: true,
        isHighAccuracy: true,
        success: function (res) {
          that.longitude = res.longitude
          that.latitude = res.latitude
          // 标记
          that.marker[0].latitude = res.latitude
          that.marker[0].longitude = res.longitude
          console.log('当前位置的经度：' + res.longitude)
          console.log('当前位置的纬度：' + res.latitude)
          wx.request({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=UWHBZ-3AEKX-5U74E-7SFQY-BRJO3-O2BUV`,
            success(val) {
              console.log(val, '定位')
              that.address = val.data.result.address
              that.address_title = val.data.result.address_reference.landmark_l2.title
            },
          })
        },
      })
    },
    back() {
      uni.navigateBack({
        delta: 1,
      })
    },
    submit() {
      uni.showLoading({ title: '提交中' })
      console.log('remark=' + this.remark)
      const data = {
        createTime: this.currentDate,
        eventTime: this.currentDate,
        location: this.address_title,
        lnglat: this.longitude + ',' + this.latitude,
        imgUrl: JSON.stringify(this.imgUrl),
        remark: this.remark,
      }
      addWorkLog(data)
        .then(res => {
          uni.hideLoading()
          uni.showToast({
            title: res.msg,
            icon: 'none',
          })
          uni.$emit('refreshData', { refresh: true })
          uni.navigateBack({
            delta: 1,
          })
        })
        .catch(err => {
          uni.hideLoading()
          uni.showToast({
            title: err.msg,
            icon: 'none',
          })
        })
    },
    deletePic(e) {
      const index = this.fileListUrl.findIndex(item => e.file.oldUrl === item.oldUrl)

      ~index && this.fileListUrl.splice(index, 1)
      ~index && this.imgUrl.splice(index, 1)
    },
    // 新增图片
    async afterRead(event) {
      console.log('event=' + JSON.stringify(event))
      const imgId = await this.uploadFilePromise(event.file.url)
      const data = {
        thumb: imgId,
        type: 'image',
        url: imgId,
        oldUrl: imgId,
      }
      console.log(imgId)
      this.fileListUrl.push(data)
      this.imgUrl.push(imgId)
    },
    async uploadFilePromise(url) {
      const _this = this

      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: url,
          success: imageInfo => {
            console.log(imageInfo)
            let scale = (350 / imageInfo.width).toFixed(2)
            const width = imageInfo.width * parseFloat(scale)
            const height = imageInfo.height * parseFloat(scale)
            console.log(scale)
            uni.compressImage({
              src: url,
              compressedWidth: width,
              compressHeight: height,
              quality: 60,
              success: async function (resurl) {
                let waterMarkFilePath = await _this.addWatermark(resurl.tempFilePath, 'shuiyin')
                console.log('waterMarkFilePath=' + waterMarkFilePath)
                _this.uniShowLoading()
                saveImage(waterMarkFilePath)
                  .then(res => {
                    _this.uniHideLoading()
                    resolve(res)
                  })
                  .catch(error => {
                    _this.uniHideLoading()
                    reject(error)
                  })
              },
              fail: function (err) {
                _this.uniHideLoading()
                reject(error)
                console.log(err)
                console.log('压缩失败：')
              },
            })
          },
        })
      })
    },

    addWatermark(imagePath, watermarkText) {
      const _this = this
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: imagePath,
          success: imageInfo => {
            console.log(imageInfo)
            const ctx = uni.createCanvasContext('watermarkCanvas') // 创建canvas上下文
            const { width, height } = imageInfo

            ctx.drawImage(imagePath, 0, 0, width, height)
            this.draw()
            // ctx.setFontSize(14) // 设置字体大小
            // ctx.setFillStyle('black') // 设置水印颜色

            // // 设置水印位置，这里以右下角为例
            // ctx.fillText(this.user.userName, 0, height - 100)
            // ctx.fillText(this.address_title, 0, height - 80)
            // ctx.fillText(this.currentDate, 0, height - 60)

            ctx.draw(false, () => {
              uni.canvasToTempFilePath({
                canvasId: 'watermarkCanvas',
                success: res => {
                  console.log('水印图片生成成功:' + res.tempFilePath)
                  resolve(res.tempFilePath)
                },
                fail: err => {
                  console.error('水印图片生成失败:' + err)
                  reject(err)
                },
              })
            })
          },
        })
      })
    },
    draw() {
      console.log('---------draw node')
      const timeData = this.formatTime()
      const date = timeData.date
      const time = timeData.time
      const week = timeData.week

      const sizeX = this.width / 375
      // 判断地址是否超出边界
      if (_this.isWrap) {
        this.height -= 15 * sizeX
      }
      ctx.setFontSize(14)
      ctx.font = `${35 * sizeX}px 黑体`
      ctx.fillStyle = '#ffffff'
      ctx.textBaseline = 'bottom'
      // 绘制时间
      ctx.fillText(time, 10 * sizeX, this.height - 30 * sizeX)
      const timeWidth = ctx.measureText(time).width
      // 绘制边框线条
      ctx.beginPath()
      ctx.lineCap = 'round'
      ctx.moveTo(timeWidth + 16 * sizeX, this.height - 59 * sizeX)
      ctx.lineTo(timeWidth + 16 * sizeX, this.height - 36 * sizeX)
      ctx.lineWidth = 1.7 * sizeX
      ctx.strokeStyle = '#A9A9A8'
      ctx.stroke()
      // 绘制年月日
      ctx.font = `${12 * sizeX}px 黑体`
      ctx.fillText(date, timeWidth + 22 * sizeX, this.height - 49 * sizeX)
      // 绘制周几
      ctx.fillText(week, timeWidth + 22 * sizeX, this.height - 34 * sizeX)
     
      // 绘制换行地址
      ctx.font = `bold ${14 * sizeX}px 黑体`
      _this.drawText(ctx, "地址", 10 * sizeX, this.height - 10 * sizeX, this.width)
    },
    // 时间转换
    formatTime() {
      const date = new Date()
      const [year, month, day, hour, minute] = [date.getFullYear(), String(date.getMonth() + 1).padStart(2, '0'), String(date.getDate()).padStart(2, '0'), String(date.getHours()).padStart(2, '0'), String(date.getMinutes()).padStart(2, '0')]
      const weekDay = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()]
      return {
        date: `${year}-${month}-${day}`,
        time: `${hour}:${minute}`,
        week: `星期${weekDay}`,
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.ditu {
  background-color: #f4f5f9;
  padding: 20rpx;
  height: 100vh;
  font-size: 28rpx;
  &_box {
    background-color: white;
    border-radius: 10rpx;
    padding: 20rpx;
    margin-top: 20rpx;

    .row {
      display: flex;
      justify-content: space-between;
      height: 80rpx;
      line-height: 80rpx;
      .label {
        color: #888;
        font-size: 26rpx;
      }
    }
    .border-bottom {
      border-bottom: 1rpx solid #f1f1f1;
    }
    .photoinfo {
      height: 150rpx;
      width: 150rpx;
      border-radius: 20rpx;
      position: relative;
      margin-top: 10rpx;
      image {
        height: 150rpx;
        width: 150rpx;
      }
      .showphoto {
        border-radius: 20rpx;
        width: 150rpx;
        height: 150rpx;
      }
      .del {
        /* background-color: red; */
        color: white;
        width: 30rpx;
        height: 30rpx;
        position: absolute;
        right: 10rpx;
        top: 5rpx;
        text-align: center;
        align-items: center;
        justify-content: center;
        display: flex;
        font-size: 25rpx;
        line-height: 30rpx;
      }
    }
  }
  .bottom {
    display: flex;
    align-items: center;
    position: absolute;
    height: 150rpx;
    bottom: 0;
    background-color: white;
    left: 0;
    right: 0;
    .btn {
      background-color: #2f6fef;
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      color: white;
      border-radius: 50rpx;
      margin-left: 20rpx;
      margin-right: 20rpx;
      font-size: 28rpx;
    }
    .back {
      background-color: white;
      color: #333;
      border: 1rpx solid #cbd2de;
    }
  }
}
.canvas-view {
  position: fixed;
  top: -99999999rpx;
}
.canvas {
  width: 250px;
  height: 444px;
  opacity: 0;

  z-index: -999;
}
</style>
